import createRouter from '@/uni_modules/zzh-simple-router/js_sdk/router/router.js'

const router = createRouter()
router.encode = 0

const whiteList = ['pages/index/index', 'pages/login/login', 'pages/login/register',
	'pages/login/forget'
] // 除了这些路径，其他都必须登录

const tabbar = ['pages/user/info']
// 全局路由拦截器
router.before = function(from, next) {
	// //console.log("before", hasPermission(from.url))

	if (hasPermission(from.url)) {
		next()
	} else {
		uni.showModal({
			title: '温馨提示',
			content: '你还没有登录，请先登录',
			success: (res) => {
				// //console.log("res", res);
				if (res.confirm) {
					// next({ url: 'pages/login/index' })
					next('pages/login/login')

				}
			}
		})

	}
	// return true

}

router.after = to => {
	// // //console.log(to);
	return to
}

router.onError = err => {
	// //console.log(err)
}

function hasPermission(url) {
	url = url.split('?')[0]
	let islogin = uni.getStorageSync("isLogin");
	islogin = Boolean(islogin); //返回布尔值
	// // //console.log(islogin,"是否登录");
	// 在白名单中或有登录判断条件可以直接跳转

	if (whiteList.find(rule => (url).includes(rule)) || islogin) { //如果查到是白名单就为true，如果没有查到，登录了，也是true
		return true
	}
	return false

}

uni.addInterceptor('switchTab', {
	// tabbar页面跳转前进行拦截	
	invoke(e) {
		// //console.log(e, "路由拦截");
		let islogin = uni.getStorageSync("isLogin");
		// //console.log("路由拦截hasPermission", hasPermission(e.url))
		if (hasPermission(e.url)) {
			return true
		} else {
			uni.navigateTo({
				url: `/pages/login/login?istabbar=true&url=${e.url}`
			})
			return false
		}

	},
	success(e) {}
})


export default router